<?php
/**
 * Created by PhpStorm.
 * User: Lxx<779219930@qq.com>
 * Date: 2016/4/21
 * Time: 15:58
 */

namespace app\home\controller;
use app\home\model\Collect;
use app\home\model\Comment;
use app\home\model\Like;
use app\user\model\WechatUser;
use com\wechat\TPQYWechat;
use com\wechat\TPWechat;
use think\Config;
use think\Controller;
use think\Db;
use app\home\model\Picture;
use app\home\model\Browse;

class Base extends Controller {
    public function _initialize(){
//        session('userId','13732477330'); //总经理
//        session('userId','13858544625'); //副总 经理
//        session('userId','13626867257');
//        session('userId','15957502511'); //副总田
//        session('userId','13705857457'); //科室长
//        session('userId','15967529895'); //办公室主任
//        session('userId','15157525892'); //副职
//        session('userId','13675733637'); //考勤上报
//        session('userId','15857546760'); //普通成员
//        session('userId','visitor'); //游客
//        session('userId',''); //游客

//        session('header','/home/images/vistor.jpg');
//        session('nickname','游客');
        if(!empty($_SERVER['REQUEST_URI'])){
            session('requestUri', $_SERVER["REQUEST_URI"]);
        }
        $userId = session('userId');

        if(Config::get('WEB_SITE_CLOSE')){
            return $this->error('站点维护中，请稍后访问~');
        }
        //如果是游客的话默认userid为visitors
        if($userId == 'visitor'){
            session('nickname','游客');
            session('header','/home/images/vistor.jpg');
        }else{
            //微信认证
            $Wechat = new TPQYWechat(Config::get('user'));
            // 1用户认证是否登陆
            if(empty($userId)) {
                $redirect_uri = Config::get("user.login");
                $url = $Wechat->getOauthRedirect($redirect_uri);
                $this->redirect($url);
            }

            // 2获取jsapi_ticket
            $jsApiTicket = session('jsapiticket');
            if(empty($jsApiTicket) || $jsApiTicket=='') {
                session('jsapiticket', $Wechat->getJsTicket()); // 官方7200,设置7000防止误差
            }
        }
    }

    /**
     * 判断是否是游客登录
     */
    public function anonymous() {
        $userId = session('userId');
        //如果userId等于visitor  则为游客登录，否则则正常显示
        if($userId == 'visitor'){
            $this->assign('visit', 1);
        }else{
            //离退休给跳转走
            $leaveUserDepart = WechatUser::where('userid',$userId)->value('department');
            if(empty($leaveUserDepart) || $leaveUserDepart == 39) {
                return $this->fetch('/public/500');
            }
            $this->assign('visit', 0);
        }
    }

    /*
     * 判断  是否 游客访问
     */
    public function checkRole(){
        $userId = session('userId');
        //如果userId等于visitor  则为游客登录，否则则正常显示
        if($userId == 'visitor'){
//            return $this ->error('抱歉,游客暂无相关权限!',Url('Constitution/game'));
            $this->redirect('Verify/null');
        }
    }
    /**
     * 获取企业号签名
     */
    public function jssdk(){
        $Wechat = new TPQYWechat(Config::get('user'));
        $url = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $jsSign = $Wechat->getJsSign($url);
        $this->assign("jsSign", json_encode($jsSign));
    }

    /**
     * 默认图片
     * $front_pic 封面图片id：1-10
     * $list_pic 列表图片id：35-44
     * $carousel_pic 轮播图片id: 45-54
     */
    public function default_pic(){
        //随机封面图
        $a = array('1'=>'a','2'=>'b','3'=>'c','4'=>'d','5'=>'e','6'=>'f','7'=>'g','8'=>'h','9'=>'i','10'=>'j','11'=>'k','12'=>'l','13'=>'m','14'=>'n','15'=>'o');
        $front_pic = array_rand($a,1);
        return $front_pic;
    }

    /**
     * 点赞，$type,$aid
     * type值：
     * 0 评论点赞
     * 1 公司简讯
     * 2 公司发文
     * 3 党群建设
     */
    public function like(){
        $uid = session('userId'); //点赞人
        $type = input('type'); //获取点赞类型
        $aid = input('aid');
        switch ($type) {    //根据类别获取表明
            case 0:
                $table = "comment";
                break;
            case 1:
                $table = "news_issued";
                break;
            case 2:
                $table = "news_letter";
                break;
            case 3:
                $table = "construction";
                break;
            default:
                return $this->error("无该数据表");
                break;
        }
        $likeModel = new Like();
        $data = array(
            'type' => $type,
            'table' => $table,
            'aid' => $aid,
            'uid' => $uid,
        );
        $final_data = $this->check_data($data,2);
        $like = $likeModel->where($data)->find();
        if(empty($like)) {  //点赞
            $res = $likeModel->create($final_data);
            if($res) {
                //文章点赞成功积分+1
                if($data['type'] != 0) {
                    WechatUser::where('userid',$uid)->setInc('score',1);
                }
                //更新数据
                Db::name($table)->where('id',$aid)->setInc('likes');
                return $this->success("点赞成功");
            }else {
                return $this->error("点赞失败");
            }
        }else { //取消
            $result = $likeModel::where($data)->delete();
            if($result) {
                //取消成功积分-1
                if($data['type'] != 0) {
                    WechatUser::where('userid',$uid)->setDec('score',1);
                }
                Db::name($table)->where('id',$aid)->setDec('likes');
                return $this->success("取消成功");
            }else {
                return $this->error("取消失败");
            }
        }
    }

    /**
     * 收藏文章
     */
    public function collect(){
        $uid = session('userId'); //用户id
        $type = input('type'); //获取收藏类型
        $aid = input('aid');
        switch ($type) {    //根据类别获取表明
            case 1:
                $table = "news_issued";
                break;
            case 2:
                $table = "news_letter";
                break;
            case 3:
                $table = "construction";
                break;
            default:
                return $this->error("无该数据表");
                break;
        }
        $collectModel = new Collect();
        $data = array(
            'type' => $type,
            'table' => $table,
            'aid' => $aid,
            'uid' => $uid,
        );
        $final_data = $this->check_data($data,3);
        $collect = $collectModel->where($data)->find();
        if(empty($collect)) {  //收藏
            $res = $collectModel->create($final_data);
            if($res) {
                if($data['type'] != 0) {
                    WechatUser::where('userid',$uid)->setInc('score',1);
                }
                //更新数据
                Db::name($table)->where('id',$aid)->setInc('collect');
                return $this->success("收藏成功");
            }else {
                return $this->error("收藏失败");
            }
        }else { //取消
            $result = $collectModel::where($data)->delete();
            if($result) {
                if($data['type'] != 0) {
                    WechatUser::where('userid',$uid)->setDec('score',1);
                }
                Db::name($table)->where('id',$aid)->setDec('collect');
                return $this->success("取消成功");
            }else {
                return $this->error("取消失败");
            }
        }
    }

    /**
     * 评论，$type,$aid,$content
     * type值： 参考like方法注释
     */
    public function comment(){
        if(IS_POST){
            $uid = session('userId');
            $type = input('type');
            $aid = input('aid');
            switch ($type) {    //根据类别获取表明
                case 1:
                    $table = "news_issued";
                    break;
                case 2:
                    $table = "news_letter";
                    break;
                case 3:
                    $table = "construction";
                    break;
                default:
                    return $this->error("无该数据表");
                    break;
            }
            $commentModel = new Comment();
            $data = array(
                'content' => input('content'),
                'type' => $type,
                'aid' => $aid,
                'uid' => $uid,
                'table' => $table,
            );
            $final_data = $this->check_data($data,1);
            $res = $commentModel->create($final_data);
            if($res) {  //返回comment数组
                if($final_data['score'] == 1) {   //当天只增加一次数值
                    WechatUser::where('userid',$uid)->setInc('score',1);    //评论成功增加1分
                }
                //更新主表数据
                $map['id'] = $res['aid'];   //文章id
                $model = Db::name($table)->where($map)->setInc('comments');
                if($model) {
                    $user = WechatUser::where('userid',$uid)->find();    //获取用户头像和昵称
                    $nickname = ($user['nickname']) ? $user['nickname'] : $user['name'];
                    $header =  ($user['header']) ? $user['header'] : $user['avatar'];
                    //返回用户数据
                    $jsonData = array(
                        'id' => $res['id'],
                        'time' => date("Y-m-d",time()),
                        'content' => input('content'),
                        'nickname' => $nickname,
                        'header' => $header,
                        'type' => $type,
                        'create_time' => time(),
                        'likes' => 0,
                        'status' => 1,
                    );
                    return $this->success("评论成功","",$jsonData);
                }else {
                    return $this->error("评论失败");
                }
            }else {
                return $this->error($commentModel->getError());
            }
        }
    }

    /**
     * 加载更多评论
     */
    public function morecomment(){
        $uid = session('userId');
        $len = input('length');
        $map = array(
            'type' => input('type'),
            'aid' => input('aid'),
        );
        //敏感词屏蔽
        $badword = array(
            '法轮功','法轮','FLG','六四','6.4','flg'
        );
        $badword1 = array_combine($badword,array_fill(0,count($badword),'***'));
        $comment = Comment::where($map)->order('likes desc,create_time desc')->limit($len,8)->select();
        if($comment) {
            foreach ($comment as $value) {
                $user = WechatUser::where('userid',$value['uid'])->find();
                $value['nickname'] = $user ? $user['name'] : "无该用户";
                $value['header'] = ($user['header']) ? $user['header'] : $user['avatar'];
                $value['time'] = date('Y-m-d',$value['create_time']);
                $value['content'] = strtr($value['content'], $badword1);
                $map1 = array(
                    'type' => 0,
                    'aid' => $value['id'],
                    'uid' => $uid,
                    'status' => 0,
                );
                $like = Like::where($map1)->find();
                ($like) ? $value['is_like'] = 1 : $value['is_like'] = 0;
            }
            return $this->success("加载成功","",$comment);
        }else{
            return $this->error("没有更多");
        }
    }

    /**
     * 评论删除
     * @throws \think\Exception
     * @throws \think\Exception\DbException
     * @throws \think\exception\PDOException
     */
    public function commentdel(){
        if(IS_POST) {
            $id = input('id');
            $comment = Comment::get($id);
            $res = Comment::where('id',$id)->delete();
            if($res) {
                Db::table("zm_".$comment['table'])->where('id',$comment['aid'])->setDec('comments',1);
                return $this->success("删除成功");
            }else {
                return $this->error("删除失败");
            }
        }
    }

    /**
     * 判断当天数据库是否存在数据
     * 评论： $cl-> 1
     * 点赞： $cl-> 2
     * 收藏： $cl-> 3
     */
    public function check_data($data,$cl) {
        if($cl == 1) {
            $commentModel = new Comment();
            $map = $data;
            unset($map['content']);
            $start = mktime(0,0,0,date("m"),date("d"),date("Y"));
            $end = mktime(23,59,59,date("m"),date("d"),date("Y"));
            $map['create_time'] = ["between",[$start,$end]];
            $count = count($commentModel->where($map)->select());
            if($count < 1) {
                $data['score'] = 1;
            }else {
                $data['score'] = 0;
            }
        }else if($cl == 2) {
            if($data['type'] == 0) {
                $data['score'] = 0;
            }else {
                $data['score'] = 1;
            }
        }else {
            $data['score'] = 1;
        }
        return $data;
    }

    /**
     * 浏览记录
     * type值： 参考like方法注释
     */
    public function browser($type,$uid,$aid)
    {
        switch ($type) {    //根据类别获取表明
            case 1:
                $table = "news_issued";
                break;
            case 2:
                $table = "news_letter";
                break;
            case 3:
                $table = "construction";
                break;
            default:
                return $this->error("无该数据表");
                break;
        }
        $data = array(
            'type' => $type,
            'uid' => $uid,
            'aid' => $aid,
            'table' => $table
        );
        $browserModel = new Browse();
        $history = $browserModel->where($data)->find();

        if (!$history && $aid != 0) {
            $browserModel->create($data);
            WechatUser::where('userid', $uid)->setInc('score',1);
        }
    }

    /**
     * 获取详情
     * */
    public function content($type,$id){
        $userId = session('userId');
        switch ($type) {    //根据类别获取表明
            case 1:
                $table = "news_issued";
                break;
            case 2:
                $table = "news_letter";
                break;
            case 3:
                $table = "construction";
                break;
            default:
                return $this->error("无该数据表");
                break;
        }
        //浏览加一
        Db::name($table)->where('id',$id)->setInc('views');
        if($userId != "visitor"){
            //浏览不存在则存入zm_browse表
            $this->browser($type,$userId,$id);
        }
        //活动基本信息
        $list = Db::name($table)->find(['id' => $id]);
        if (empty($list)){
            $this ->error('该内容不存在或已删除!');
        }
        $list['user'] = $userId;
        //分享图片及链接及描述
        if (isset($list['front_cover'])){ // 封面图
            if (empty($list['front_cover'])){
                $list['share_image'] = '/home/images/common/default.png';  // 默认
            }else{
                $image = Picture::where('id',$list['front_cover'])->find();
                $list['share_image'] = "http://".$_SERVER['SERVER_NAME'].$image['path'];
            }
        }else{
            $list['share_image'] = '/home/images/common/default.png';  // 默认
        }
        if (isset($list['description'])){
            if (empty($list['description'])){
                if (!isset($list['content'])){
                    $list['desc'] = '查看详情';
                }else{
                    $list['desc'] = str_replace('&nbsp;','',strip_tags($list['content']));
                }
            }else{
                $list['desc'] = $list['description'];
            }
        }else{
            if (!isset($list['content'])){
                $list['desc'] = '查看详情';
            }else{
                $list['desc'] = str_replace('&nbsp;','',strip_tags($list['content']));
            }
        }
        $list['link'] = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REDIRECT_URL'];
        //获取 文章点赞
        $likeModel = new Like();
        $like = $likeModel->getLike($type,$id,$userId);
        $list['is_like'] = $like;
        //获取 评论
        $commentModel = new Comment();
        $comment = $commentModel->getComment($type,$id,$userId);
        $list['comment'] = $comment;
        //获取 收藏
        $collectModel = new Collect();
        $collect = $collectModel->getCollect($type,$id,$userId);
        $list['is_collect'] = $collect;
        return $list;
    }

    /**
     * 获取封面图片
     */
    public function get_cover($id) {
        $path = Picture::get($id);
        $return = $path ? $path['path'] : "";
        return $return;
    }
}